var app = getApp();
var socket = null;
var socketOpen = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderlist: {},
    listnum1: 0,
    now_page: 1,
    minute: '00',
    second: '00',
    timenum: 0,
    timer: [],
    timer2: [],
    sendtimer: '',
    orderlist2: {},
    listnum2: 0,
    msg_num:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getorder();
    this.webSocketStart();
  
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //this.getorder();
    this.getMsgNUm();
  },
  // 获取抢单信息
  getorder: function () {
    var that = this;
    var shopid = wx.getStorageSync("shop_id");
    var param = {
      url: "api/shop/orders",
      data: {
        shop_id: shopid,
      },
      success: function (e) {
        var order = e.data.data.list;
        order = JSON.parse(order);
        console.log(order)
        var listnum1 = Object.keys(order).length;
        that.setData({
          listnum1: listnum1
        })
        console.log(listnum1)
        if (listnum1 > 0) {
          for (let x in order) {
            console.log(x)
            console.log(order[x].order_seconds)
            var timenum = order[x].order_seconds;
            that.countDown(order, x, timenum);
          }

        }


      }
    };
    app.post(param);
  },
  // 倒计时
  countDown: function (order, i, num) {
    var that = this;
    var time = num;

    that.data.timer[i] = setInterval(function () {
      if (parseInt(time) > 1) {
        time--;
        // 获取天、时、分、秒
        let min = parseInt(time / 60);
        let sec = parseInt(time % 60);
        order[i].seconds = that.timeFormat(min) + ':' + that.timeFormat(sec);
      } else {
        //order.splice(i,1);
        clearInterval(that.data.timer[i]);
        delete order[i]
      }
      // console.log(order)
      that.setData({
        orderlist: order
      })
    }, 1000)

  },

  countDown2: function (order, i, num) {
    var that = this;
    var time = num;
    console.log(i)
    var orderlist2 = that.data.orderlist2;
    orderlist2[i] = order[i];

    that.data.timer2[i] = setInterval(function () {
      if (parseInt(time) > 1) {
        time--;
        // 获取天、时、分、秒
        let min = parseInt(time / 60);
        let sec = parseInt(time % 60);
        //console.log(orderlist2[i])
        orderlist2[i].seconds = that.timeFormat(min) + ':' + that.timeFormat(sec);

      } else {
        clearInterval(that.data.timer2[i])
        // order.splice(i, 1);
        delete that.data.orderlist2[i]
      }
      that.setData({
        orderlist2: orderlist2
      })
    }, 1000)


  },

  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },
  lishi: function () {
    wx.navigateTo({
      url: '/pages/shangjia/lishi/lishi',
    })
  },


  /***************************/
  //开始webSocket
  webSocketStart(e) {
    socket = wx.connectSocket({
      url: "wss://m.guaiguaixiu.com:2000",
      header: { 'content-type': 'application/json' },
      success: res => {
        console.log('小程序连接成功：', res);
      },
      fail: err => {
        console.log('出现错误啦！！' + err);
        wx.showToast({
          title: '网络异常！',
        })
      }
    })

    this.webSokcketMethods();

  },

  //监听指令
  webSokcketMethods(e) {
    let that = this;
    socket.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res);
      that.data.sendtimer = setInterval(function () {
        that.sendSocketMessage(1);
      }, 50000)
    })
    socket.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
    })
    socket.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
    })

    socket.onMessage(onMessage => {
      var data = JSON.parse(onMessage.data);
      console.log(data);
      if (parseInt(data.type) == 2) {
        that.bdshopid(data.connectionID, data.workerID);
      }
      if (parseInt(data.type) == 1) {
        that.getdetail(data.grab_orders_id);
      }
      if (parseInt(data.type) == 3) {
        var orderid = data.grab_orders_id;
        if (that.data.orderlist[orderid]) {
          console.log(that.data.orderlist[orderid])
          delete that.data.orderlist[orderid];
          clearInterval(that.data.timer[orderid]);
        } else {
          console.log(that.data.orderlist2[orderid])
          delete that.data.orderlist2[orderid];
          clearInterval(that.data.timer2[orderid]);
        }
        that.setData({
          orderlist: that.data.orderlist,
          orderlist2: that.data.orderlist2
        })
      }
    })

  },
  // 绑定shopid
  bdshopid: function (connectionID, workerID) {
    var shopid = wx.getStorageSync('shop_id');
    var param = {
      url: 'api/shop/uploadWorker',
      data: {
        shop_id: shopid,
        connection_id: connectionID,
        worker_id: workerID
      },
      success: function (res) {
        console.log(res)
      }

    };
    app.post(param);
  },
  // 获取详情信息
  getdetail: function (id) {
    var that = this;
    var param = {
      url: 'api/shop/getIndexOrderDetail',
      data: {
        grab_orders_id: id
      },
      success: function (res) {
        console.log(res)
        var order = res.data.data.list;
        // order = JSON.parse(order);
        console.log(order)
        var listnum2 = Object.keys(order).length;
        console.log(listnum2)
        that.setData({
          listnum2: listnum2
        })

        for (let x in order) {
          console.log(x)
          var timenum = order[x].order_seconds;
          console.log(timenum)
          if (parseInt(order[x].order_status) == 0) {
            that.countDown2(order, x, timenum);
          } else if (parseInt(order[x].order_status) != 0) {
            delete that.data.orderlist2[x];
            // that.setData({
            //   orderlist2: that.data.orderlist2
            // })
          }
        }
      }
    };
    app.post(param);
  },
  //发送消息
  sendSocketMessage(msg) {
    let that = this;
    if (socketOpen) {
      console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
      socket.send({
        data: JSON.stringify(msg)
      }, function (res) {
        console.log('已发送', res)
      })
    }

  },
  //关闭连接
  closeWebsocket(str) {
    if (socketOpen) {
      socket.close(
        {
          code: "1000",
          reason: str,
          success: function () {
            console.log("成功关闭websocket连接");
          }
        }
      )
    }
  },

  /***************************/
  onHide: function () {
    // this.closeWebsocket();
    // clearInterval(this.data.sendtimer);
  },
  onUnload: function () {
    this.closeWebsocket();
    clearInterval(this.data.sendtimer);
  },
  getMsgNUm: function () {
    let url = 'api/shopr/getMsgNum';
    var data = {
      url: url,
      data: {
        shop_id: wx.getStorageSync('shop_id')
      },
      success: (e) => {
        this.setData({
          msg_count: e.data.data.count
        });
      }
    };
    app.post(data);
  }

})